using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;

using System.IO;
using CoolEngine.Engine.Scripting;
using System.ComponentModel;
using IronPython.Compiler;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Compiler.Ast;

namespace ContentExtensions
{
    /// <summary>
    /// Imports a python script.
    /// </summary>
    [ContentImporter(".py", DisplayName = "Python script importer", DefaultProcessor = "PythonSourceProcessor")]
    public class PythonImporter : ContentImporter<string>
    {
        public override string Import(string filename, ContentImporterContext context)
        {
            var engine = PythonEngine.CurrentEngine;
            SourceUnit unit = HostingHelpers.GetSourceUnit(engine.CreateScriptSourceFromFile(filename));

            var compilerOptions = new IronPython.Compiler.PythonCompilerOptions();
            ErrorSink sink = ErrorSink.Default;
            CompilerContext compilerContext = new CompilerContext(unit, compilerOptions, sink);

            Parser parser = Parser.CreateParser(compilerContext, new IronPython.PythonEngineOptions() { PerfStats = true });
            try
            {
                PythonAst ast = parser.ParseFile(true);
                ast.Walk(new PythonImportWalker() { Context = context, Path = Path.GetDirectoryName(filename) });
            }
            catch (SyntaxErrorException e)
            {
                throw new SyntaxErrorException(e.Message + " at " + e.Line + "," + e.Column, e);
            }
            return File.ReadAllText(filename);
        }
    }
    public class PythonImportWalker:PythonWalker
    {
        public ContentImporterContext Context { get; set; }
        public string Path { get; set; }
        public override bool Walk(ImportStatement node)
        {
            foreach (DottedName import in node.Names)
            {
                string name = import.MakeString();
                if (System.IO.File.Exists(System.IO.Path.Combine(Path, name + ".py")))
                {
                    Context.AddDependency(name);
                }                
            }
            return base.Walk(node);
        }
    }
}
